import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Input } from 'antd';
import styles from './../Users.css';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataTableCreate from '../../addons/DataTable'
import dataEditCreate from '../../addons/DataEdit'
import * as IndiDiviService from '../../../services/AccountDivi';
const daoName = "IndiAccoDiviSq";
const ButtonGroup = Button.Group;
const renderReplace = (data) => {
    let value = ''
    if (data !== "1900-01-01T00:00:00Z") {
        value = data.replace("T", " ").replace("Z", "")
    }
    return value
};
const columns = [
    { title: '开户网点', dataIndex: 'KHWD', key: 'KHWD', width: 140, dispaly: true },
    { title: '开户日期', width: 110, sorter: true, key: 'KHR', caption: "KHR", render: data => datetime.format(data.KHR, "yyyy-MM-dd"), dispaly: true },
    // { title: '账号', dataIndex: 'ZH', key: 'ZH', width: 150, dispaly: true },
    // { title: '卡号', dataIndex: 'KH', key: 'KH', width: 150, dispaly: true },
    { title: '客户名称', dataIndex: 'KHMC', key: 'KHMC', width: 140, dispaly: true },
    { title: '证件号码', dataIndex: 'ZJHM', key: 'ZJHM', width: 180, dispaly: true },
    { title: '申请时间', width: 180, sorter: true, key: 'TJRQ', caption: "TJRQ", render: data => renderReplace(data.TJRQ), dispaly: true },
    { title: '审批时间', width: 180, sorter: true, key: 'SPSJ', caption: "SPSJ", render: data => renderReplace(data.SPSJ), dispaly: true },
    { title: '客户经理', width: 120, key: 'EMID', caption: "User.Name", render: data => data.User.Name, dispaly: true },
    { title: '分成比例', width: 80, dataIndex: 'DSVL', key: 'DSVL', dispaly: true },
    { title: '当前状态', width: 100, key: 'ISTY', dataIndex: 'ISTYCaption', dispaly: true },
    { title: '原因', width: 250, dataIndex: 'YY', key: 'YY', dispaly: true },
];
const controls = [
    { name: 'KHWD', required: true, type: 'text', label: '开户网点', grid: 12 / 24 },
    { name: 'KHR', required: true, type: 'date', label: '开户日期', grid: 12 / 24 },
    // { name: 'ZH', required: true, type: 'text', label: '账号', grid: 12 / 24 },
    // { name: 'KH', required: true, type: 'text', label: '卡号', grid: 12 / 24 },
    { name: 'KHMC', required: true, type: 'text', label: '客户名称', grid: 12 / 24 },
    { name: 'ZJHM', required: true, type: 'text', label: '证件号码', grid: 12 / 24 },
    { name: 'TJRQ', required: true, type: 'date', label: '申请时间', grid: 12 / 24 },
    { name: 'SPSJ', required: true, type: 'date', label: '审批时间', grid: 12 / 24 },
    { name: 'YY', required: true, type: 'text', label: '原因', grid: 12 / 24 },
];
const DataTable = dataTableCreate(daoName);
const EditFrom = dataEditCreate(daoName);
class GrckrdspForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataChange: false,
            dataList:[]
        };
    }
    componentDidMount() {
        this.props.dispatch({
            type: `${daoName}/setKeyName`,
            payload: { keyName: "ID", permID: this.props.permID }
        });
        let { orgID, pOrgID, popedomTypes, permID } = this.props
        const pTypes = popedomTypes[permID]
        let whereItems = [];
        let WhereCauses = [];
        console.log(pTypes)

        //权限控制
        if (pTypes.indexOf('4') === -1) {
            if (pTypes.indexOf('3') !== -1  && pTypes.indexOf('J') === -1) {
                whereItems.push({
                    FieldName: "OrganID",
                    Operator: "=",
                    FieldValues: '' + orgID
                }, {
                        FieldName: "ISTY",
                        Operator: "in",
                        FieldValues: ''+0
                    });
            } else if (pTypes.indexOf('J') !== -1) {
                whereItems.push({
                    FieldName: "ParentOrganID",
                    Operator: "=",
                    FieldValues: '' + pOrgID
                }, {
                        FieldName: "ISTY",
                        Operator: "in",
                        FieldValues: ''+0
                    });
            }
            WhereCauses.push({
                WhereItems: whereItems,
                RelationSign: "AND"
            })
        } else {
            whereItems.push({
                FieldName: "ISTY",
                Operator: "in",
                FieldValues: ''+0
            })
            WhereCauses.push({
                WhereItems: whereItems,
                RelationSign: "AND"
            })
        }
        let seeks = WhereCauses
        let sort = {
            field: 'TJRQ',
            order: 'descend'
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort, seeks: seeks }
        });
        this.loadOptionData();
    }
    loadOptionData() {
        let options = []
        controls.map(c => {
            if (c.fetch) {
                let f = c.fetch;
                if (c.type === 'cascader-select') {
                    f.isCascader = true;
                }
                if (c.type !== 'search') {
                    options.push(f);
                }
            }
        })
        if (daoName && options.length > 0) {
            this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
        }
    }
    onSelectChangeHandler(newList, delKeys) {
        let dataList = this.state.dataList
        newList.map(data => {
            dataList.push(data)
        })
        delKeys.map(key => {
            const index = dataList.findIndex(divi => divi["ID"] === key)
            dataList.splice(index, 1)
        })
        this.setState({ dataList })
    }
    SelZT(v) {
        let whereItems = [];
        let WhereCauses = [];
        let dqzt = ""
        if (v === "all") {
            dqzt = "0,1,2"
        } else {
            dqzt = v
        }
        let { orgID, pOrgID, popedomTypes, permID } = this.props
        const pTypes = popedomTypes[permID]
        //权限控制
        if (pTypes.indexOf('4') === -1) {
            if (pTypes.indexOf('3') !== -1  && pTypes.indexOf('J') === -1) {
                whereItems.push({
                    FieldName: "OrganID",
                    Operator: "=",
                    FieldValues: '' + orgID
                }, {
                        FieldName: "ISTY",
                        Operator: "in",
                        FieldValues: dqzt
                    });
            } else if (pTypes.indexOf('J') !== -1) {
                whereItems.push({
                    FieldName: "ParentOrganID",
                    Operator: "=",
                    FieldValues: '' + pOrgID
                }, {
                        FieldName: "ISTY",
                        Operator: "in",
                        FieldValues: dqzt
                    });
            }
            WhereCauses.push({
                WhereItems: whereItems,
                RelationSign: "AND"
            })
        } else {
            whereItems.push({
                FieldName: "ISTY",
                Operator: "in",
                FieldValues: dqzt
            })
            WhereCauses.push({
                WhereItems: whereItems,
                RelationSign: "AND"
            })
        }
        let seeks = WhereCauses
        let sort = {
            field: 'TJRQ',
            order: 'descend'
        }
        this.props.dispatch({
            type: `${daoName}/fetch`,
            payload: { daoName, page: 1, pageSize: 20, sorter: sort, seeks: seeks }
        });
    }
    showModelHandler() {
        let key = null
        this.props.dispatch({
            type: `${daoName}/openEdit`,
            payload: { key }
        });
    }
    hideEditHandler() {
        const form = this.refs.YYForm.getForm();
        form.resetFields();
        this.props.dispatch({
          type: `${daoName}/hideEdit`
        });
        this.props.dispatch({
            type: `${daoName}/setSelectedRowKeys`,
            payload: { selectedRowKeys: [] }
        });
    };
    BTY(){
        this.state.newdata = []
        let acids = []
        let rows = []
        let keys = this.props.selectedRowKeys
        // keys.map(d => rows.push(Number(d.ACID)))//循环push到数组中
        // acids = Array.from(new Set(rows))//去掉数组中重复的ACID
        if(keys.length<=0){
            message.error("请选择处理的数据行！");
            return;
        }
        this.showModelHandler();
    }
    BTYSubmit(){
        let acids = this.props.selectedRowKeys
        const form = this.refs.YYForm.getForm();
        let yy="";
        form.validateFields((err, values) => {
            if (!err) {
                yy=values.YY;
            }
        });
        Modal.confirm({
            title: '提示',
            content: `你确认不同意认定申请吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                IndiDiviService.IndiAccoDiviSqBTY({ acids,yy }
                ).then(function (data) {
                    if (data === 'OK') {
                        this.state.diviList = []
                        const form = this.refs.YYForm.getForm();
                        form.resetFields();
                        this.props.dispatch({
                            type: `${daoName}/setSelectedRowKeys`,
                            payload: { selectedRowKeys: [] }
                        });
                        message.success('审批成功！')
                    } else {
                        message.error('审批失败！' + data)
                        return;
                    }
                    this.props.dispatch({
                        type: `${daoName}/hideEdit`
                    });
                    this.componentDidMount();
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
            }
        });
    }
    TY(){
        let keys = this.props.selectedRowKeys
        if(keys.length<=0){
            message.error("请选择处理的数据行！");
            return;
        }
        let dataSource = this.state.dataList
        let snum = 0
        dataSource.map(d => {
            if(d.DSVL !="100"){
                snum = snum + Number(d.DSVL);
            }
        })
        if((snum/100)%1!==0){
            message.error("审批失败！选择的数据分配比例不是100%");
            return;
        }
        Modal.confirm({
            title: '提示',
            content: `你确认同意认定申请吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                IndiDiviService.IndiAccoDiviSqTY({ keys}
                ).then(function (data) {
                    if (data === 'OK') {
                        this.state.diviList = []
                        this.props.dispatch({
                            type: `${daoName}/setSelectedRowKeys`,
                            payload: { selectedRowKeys: [] }
                        });
                        message.success('审批成功！')
                    } else {
                        message.error('审批失败！' + data)
                        return;
                    }
                    this.props.dispatch({
                        type: `${daoName}/hideEdit`
                    });
                    this.componentDidMount();
                }.bind(this)).catch(function (ex) {
                    console.log('请求出错', ex)
                });
            }
        });
    }
    render() {     
        let { permID,showEdit,selectedRowKeys } = this.props
        const controlsFilter = [
            { name: 'ZT', required: false, type: 'select', label: '状态', grid: 4 / 24, data: [{ value: 'all', label: '全部' }, { value: '1', label: '已同意' }, { value: '0', label: '待审批' }, { value: '2', label: '已驳回' }], onChange: this.SelZT.bind(this), layout: { labelSpan: 8, wrapperSpan: 13 } },
            { name: 'BT', required: false, type: 'button-group', data: [{ value: '1', label: '同意',onClick: this.TY.bind(this) }, { value: '2', label: '不同意' ,onClick: this.BTY.bind(this)}], grid: 4 / 24 },
        ];
        const controlsYY =[
            { name: 'YY', type: 'input-large', grid: 25/ 24 },
        ]
        return (
            <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
                <div className={styles.create}>
                    <EditFrom ref="findForm" daoName={daoName} controls={controlsFilter} record={{ ZT: '0' }} selectFirst={false} clearItemMargin={true} />
                </div>
                <Modal title="不同意原因" width={400} visible={showEdit} closable={false}
                    footer={[
                    <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
                    <Button key="submit" type="primary" onClick={this.BTYSubmit.bind(this)}>提交</Button>
                    ]} style={{padding:0}}
                >
                    <EditFrom ref="YYForm" daoName={daoName} controls={controlsYY} selectFirst={false} clearItemMargin={true} />
                </Modal>
                <div>
                    <DataTable ref="ListTable" daoName={daoName} columns={columns} controls={controls} permID={permID} multiSelect={true} onSelectChange={this.onSelectChangeHandler.bind(this)}/>
                </div>
            </div>
        )
    }
}
function mapStateToProps(state) {
    const { showEdit, record, selectedRowKeys, keyName } = state[daoName];
    const { userID, orgID, pOrgID, popedomTypes } = state.menus;
    return {
        userID,
        orgID,
        pOrgID,
        popedomTypes,
        showEdit,
        selectedRowKeys,
        keyName,
        record
    }
}
GrckrdspForm = connect(mapStateToProps)(GrckrdspForm)
export default GrckrdspForm;
let render = (props) => React.createElement(GrckrdspForm, props);

let f = new Factory()
f.set("GrckrdspForm", render)